<template>
    <van-address-list 
        v-if="action=='select'"
        v-model="active"
        :list="list"
        default-tag-text="默认"
        @add="AddressAdd"
        @edit="AddressEdit"
        @select="AddressSelect"
    />
    <van-address-list 
        v-else
        v-model="active"
        :list="list"
        default-tag-text="默认"
        @add="AddressAdd"
        @edit="AddressEdit"
        @select="AddressCheck"
    />
</template>

<script setup>
    //切换选中的地址时触发 AddressSelect
    const {proxy} = getCurrentInstance()
    onMounted(()=>{
        AddressData()
    })
    let active = ref(1)
    //挂载后继续调用
    //从订单页面更改地址的状态
    let action = proxy.$route.query.action ?proxy.$route.query.action: '';
    action = ref(action)
    console.log(action.value)

    //收获地址列表
    let list = reactive([
    ])
    //定义箭头函数 
    const AddressData = async ()=>{
        //发送请求
        var result = await proxy.$POST({
            url:'/address/index',
            params:{busid:proxy.$business.value.id},
        })
        if(result.code=="0"){
            proxy.$fail(result.msg);
            return false
        }
        //查询成功将查询的值遍历出来 active 对号
        result.data.map((val)=>{
            if(val.status=="1"){//绑定id 
                active.value = val.id
            }
            list.push(
                {
                    id:val.id,
                    name: val.consignee,
                    tel: val.mobile,
                    address: val.region_text+"   "+val.address,
                    isDefault: val.status==1?true:false,
                }
            )
        })

    }
    //切换选择时 把默认值也切换
    const AddressCheck = async (item)=>{
        //发送异步请求 改变默认结果
        var resSel = await proxy.$POST({
            url:'/address/check',
            params:{
                id:item.id,
                busid:proxy.$business.value.id
            }
        })
        if(resSel == "0"){
            proxy.$fail(resSel.msg);
            return false;
        }
        list.map((value) => value.isDefault = value.id == item.id ? true : false)
        
    }

    //收获地址添加
    const AddressAdd = async () => proxy.$router.push('/address/add')

    //收获地址的编辑 点击后给他传递过去值
    const AddressEdit = async (item) => {
        proxy.$router.push({path: '/address/edit', query:{addressId:item.id}})
    }
    const AddressSelect = async (item)=>{
        //region_text自定义属性吧
        item.region_text = item.address
        proxy.$address.value = item
        proxy.$router.go(-1)
    }
        
</script>